// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let data = null
  if (event.flag == 'add') {
    data = await db.collection('SJBL_Schedule').add({
      data: {
        'user_openid': wxContext.OPENID,
        'begin_date': event.begin_date,
        'end_date': event.end_date,
        'status': event.status,
        'date': event.date,
        'type': event.type,
        'title': event.title,
        'details': event.details
      }
    })
  } else {
    data = await db.collection('SJBL_Schedule').where({
      user_openid: wxContext.OPENID,
      _id: event._id
    }).update({
      data: {
        'begin_date': event.begin_date,
        'end_date': event.end_date,
        'status': event.status,
        'type': event.type,
        'title': event.title,
        'details': event.details
      }
    })
  }
  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
    data
  }
}